package br.com.informatos.repositorio;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.informatos.modelo.entidades.Jogador;
import br.com.informatos.modelo.entidades.Time;

public class TimeRepositorio {
	
	private EntityManager manager;
	
	public TimeRepositorio(EntityManager manager) {
		this.manager = manager;
	}
	
	public void adiciona (Time time) {
		this.manager.persist(time);
	}
	
	public void remove (Long id) {
		Time time = this.procura(id);
		Query query = this.manager.createQuery("SELECT x FROM Jogador x WHERE x.time = time");
		query.setParameter("time", time);
		List<Jogador> jogadores = query.getResultList();
		for (Jogador jogador : jogadores) {
			jogador.setTime(null);
		}
		this.manager.remove(time);
	}
	
	public Time atualiza (Time time) {
		return this.manager.merge(time);
	}
	
	public Time procura (Long id) {
		return this.manager.find(Time.class, id);
	}
	
	public List<Time> getLista() {
		Query query = this.manager.createQuery("SELECT x FROM Time x");
		return query.getResultList();
	}

}
